package org.ehe.business.step.service;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.ehe.business.step.converter.MultipartFileToFileConverter;
import org.ehe.business.step.domain.ManufacturingEstimate;
import org.ehe.business.step.domain.STEPAnalysisResult;
import org.ehe.business.step.pdf.PDFGenerator;
import org.ehe.system.service.ISysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author :zhangnn
 * @className :STEPAnalyzerService
 * @description: TODO
 * @date 2025-08-05 14:44:20
 */

@Service
@Slf4j
public class STEPAnalyzerService {
    @Autowired
    private ISysOssService ossService;

    @Resource
    private PDFGenerator pdfGenerator;

    public STEPAnalysisResult analyzeSTEPFile(MultipartFile file) throws Exception {
        // 创建上传目录
        //SysOssVo upload = ossService.upload(file);
        File stepFile = MultipartFileToFileConverter.convert(file);
        // 解析STEP文件
        STEPAnalysisResult result = parseSTEPFile(stepFile);

        // 生成PDF报告
        String pdfPath = pdfGenerator.generatePDFReport(result, "电机轴架");
        result.setPdfReportPath(pdfPath);

        return result;
    }

    private STEPAnalysisResult parseSTEPFile(File stepFile) throws IOException {
        STEPAnalysisResult result = new STEPAnalysisResult();
        result.setFileName(stepFile.getName());
        result.setFileSize(stepFile.length());
        result.setAnalysisTime(LocalDateTime.now());

        String content = FileUtils.readFileToString(stepFile, StandardCharsets.UTF_8);

        // 解析STEP文件头信息
        parseHeader(content, result);

        // 解析几何实体
        parseGeometricEntities(content, result);

        // 解析材料信息
        parseMaterialInfo(content, result);

        // 估算制造信息
        estimateManufacturing(result);

        return result;
    }

    private void parseHeader(String content, STEPAnalysisResult result) {
        // 解析STEP文件头部信息
        Pattern headerPattern = Pattern.compile("FILE_DESCRIPTION\\s*\\(\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = headerPattern.matcher(content);
        if (matcher.find()) {
            result.setDescription(matcher.group(1).replaceAll("'", ""));
        }

        // 解析创建时间
        Pattern timePattern = Pattern.compile("FILE_NAME\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        matcher = timePattern.matcher(content);
        if (matcher.find()) {
            result.setCreationInfo(matcher.group(1));
        }

        // 解析单位
        Pattern unitPattern = Pattern.compile("#\\d+\\s*=\\s*\\(\\s*LENGTH_UNIT\\s*\\(\\s*\\)\\s*NAMED_UNIT\\s*\\(\\s*\\*\\s*\\)\\s*SI_UNIT\\s*\\(\\s*\\.([A-Z]+)\\.", Pattern.CASE_INSENSITIVE);
        matcher = unitPattern.matcher(content);
        if (matcher.find()) {
            result.setUnit(matcher.group(1));
        } else {
            result.setUnit("MM"); // 默认单位
        }
    }

    private void parseGeometricEntities(String content, STEPAnalysisResult result) {
        Map<String, Integer> entityCounts = new HashMap<>();

        // 统计各种几何实体
        String[] entityTypes = {
            "CARTESIAN_POINT", "DIRECTION", "VECTOR",
            "LINE", "CIRCLE", "ELLIPSE", "B_SPLINE_CURVE",
            "PLANE", "CYLINDRICAL_SURFACE", "SPHERICAL_SURFACE", "B_SPLINE_SURFACE",
            "ADVANCED_FACE", "CLOSED_SHELL", "MANIFOLD_SOLID_BREP"
        };

        for (String entityType : entityTypes) {
            Pattern pattern = Pattern.compile("#\\d+\\s*=\\s*" + entityType, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(content);
            int count = 0;
            while (matcher.find()) {
                count++;
            }
            if (count > 0) {
                entityCounts.put(entityType, count);
            }
        }

        result.setGeometricEntities(entityCounts);

        // 估算复杂度
        int totalEntities = entityCounts.values().stream().mapToInt(Integer::intValue).sum();
        if (totalEntities < 100) {
            result.setComplexity("简单");
        } else if (totalEntities < 1000) {
            result.setComplexity("中等");
        } else {
            result.setComplexity("复杂");
        }
    }

    private void parseMaterialInfo(String content, STEPAnalysisResult result) {
        // 查找材料相关信息
        Pattern materialPattern = Pattern.compile("MATERIAL_DESIGNATION\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = materialPattern.matcher(content);
        List<String> materials = new ArrayList<>();
        while (matcher.find()) {
            materials.add(matcher.group(1).replaceAll("'", ""));
        }

        if (materials.isEmpty()) {
            materials.add("未指定材料");
        }

        result.setMaterials(materials);
    }

    private void estimateManufacturing(STEPAnalysisResult result) {
        ManufacturingEstimate estimate = new ManufacturingEstimate();

        // 根据复杂度估算工期
        int baseDays = 1;
        switch (result.getComplexity()) {
            case "简单":
                estimate.setEstimatedDays(baseDays * 1);
                estimate.setMachiningHours(8);
                break;
            case "中等":
                estimate.setEstimatedDays(baseDays * 3);
                estimate.setMachiningHours(24);
                break;
            case "复杂":
                estimate.setEstimatedDays(baseDays * 7);
                estimate.setMachiningHours(56);
                break;
        }

        // 估算材料用量（基于文件大小和实体数量）
        long fileSize = result.getFileSize();
        int entityCount = result.getGeometricEntities().values().stream().mapToInt(Integer::intValue).sum();

        double estimatedVolume = Math.max(fileSize / 10000.0, entityCount / 100.0); // 简化估算
        estimate.setEstimatedMaterialVolume(estimatedVolume);

        // 估算成本
        double materialCost = estimatedVolume * 50; // 每立方单位50元
        double laborCost = estimate.getMachiningHours() * 100; // 每小时100元
        estimate.setEstimatedCost(materialCost + laborCost);

        result.setManufacturingEstimate(estimate);
    }





}
